package licode.unisop.authcenter.application.executor;

import cn.hutool.core.util.StrUtil;
import licode.unisop.authcenter.exception.CenterErrorCode;
import licode.unisop.provider.vo.SiUser;
import licode.unisop.realm.client.api.SiRealmService;
import licode.unisop.realm.client.api.SiUserService;
import licode.unisop.realm.client.dto.SiRealmDTO;
import licode.unisop.realm.client.info.SiUserSaveIn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 定义统一认证平台中心领域相关接口
 *
 * @author licode
 */
@Service
public class CenterRealmExecutor {
    @Resource
    private SiRealmService siRealmService;

    @Resource
    private SiUserService siUserService;

    /**
     * 保存领域信息
     */
    @Transactional(rollbackFor = Throwable.class, timeout = 60)
    public void save(SiRealmDTO realm) {
        realm.setUpdateTime(LocalDateTime.now());
        siRealmService.saveRealm(realm);
    }

    /**
     * 保存领域用户信息
     */
    public void saveUser(SiUserSaveIn saveIn) {
        SiUser user = saveIn.getUser();
        if (StrUtil.isBlank(user.getRealmId())) {
            throw CenterErrorCode.REALM_ID_IS_BLANK.buildException();
        }

        if (null == user.getPhone()) {
            user.setPhone("");
        }

        if (null == user.getName()) {
            user.setName("");
        }

        if (StrUtil.isBlank(user.getNickName())) {
            user.setNickName(user.getName());
        }

        siUserService.saveUser(user);
    }
}
